package com.chenxin.wms.process.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.TaskEntity;
import com.chenxin.wms.mapper.TaskMapper;
import com.chenxin.wms.process.task.ITaskProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TaskProcessImpl implements ITaskProcess {
    @Autowired
    private TaskMapper taskMapper;

    @Override
    public ProcResult procWmsTaskInsert(TaskEntity taskEntity) {
        // 对要创建任务信息进行校验（任务是否重复、同一容器是否存在多个业务场景的任务等）
        if (taskEntity == null) {
            return ProcResult.error("task_insert_err#001", "待写入【任务信息】不能为空");
        }
        String fromContNo = taskEntity.getFromContNo();
        String fromPosition = taskEntity.getFromPosition();
        String taskSubType = taskEntity.getTaskSubType();
        if (StringUtils.isBlank(fromContNo)) {
            return ProcResult.error("task_insert_err#002", "待写入【任务信息】的【来源容器】不能为空");
        }
        if (StringUtils.isBlank(fromPosition)) {
            return ProcResult.error("task_insert_err#003", "待写入【任务信息】的【来源位置】不能为空");
        }

        // 判断当前LPN是否存在其他业务场景的任务
        QueryWrapper<TaskEntity> taskSubTypeQuery = new QueryWrapper<>();
        taskSubTypeQuery.lambda().eq(TaskEntity::getFromContNo, fromContNo)
                .lt(TaskEntity::getTaskStatus, "2")
                .ne(TaskEntity::getTaskSubType, taskSubType);
        Long count = taskMapper.selectCount(taskSubTypeQuery);

        // 存在其他业务场景的任务则报错
        if (count > 0) {
            return ProcResult.error("task_insert_err#005", "当前托盘【" + fromContNo + "】已存在其他业务场景的任务");
        }
        // 写入数据库
        int rows = taskMapper.insert(taskEntity);
        if (rows == 0) {
            return ProcResult.error("task_insert_err#00x", "写入【任务信息】失败");
        }
        return ProcResult.success("成功写入任务【" + taskEntity.getTaskId() + "】");
    }
}
